const router = require('koa-router')();
const userService = require('../controllers/mySqlConfig');

//当前js公共前缀
router.prefix('/diary');

// 根据前端传给我的类型，查找对应的文章列表
// 创建接口
router.post('/findNoteListByType', async (ctx, next) => {
    let note_type = ctx.request.body.note_type;
    console.log(note_type);
    await userService.findNoteListByType(note_type)
        .then(res => {
            // console.log(res);
            // if(res.length){//数据库有数据
            ctx.body = {
                code: 200,
                data: res,
                mess: '查找成功'
                // }
            }
        })
        .catch(err => {
            ctx.body = {
                code: '80001',
                data: '没找到',
                mess: '查找失败'
            }
        })
})

// 根据前端传递的id，查找对应文章的详情
router.get('/findNoteDetailById', async (ctx, next) => {
    // console.log(ctx.request.body);post拿数据
    console.log(ctx.query.id);
    let id = ctx.query.id;
    await userService.findNoteDetailById(id)
        .then(res => {
            if (res.length) {
                ctx.body = {
                    code: 200,
                    data: res,
                    mess: '查找成功'
                }
            } else {
                ctx.body = {
                    code: 200,
                    data: '没有数据',
                    mess: '查找成功'
                }
            }
        })
        .catch(err => {
            ctx.body = {
                code: '80001',
                data: err,
                mess: '查找失败'
            }
        });
})

// 发布日记
router.post('/publishNote', async (ctx, next) => {
    // 拿到前端给我的参数
    // let obj=ctx.request.body;
    // console.log(obj);
    let { useId, title, note_type, note_content, c_time, m_time, head_img, nickname } = ctx.request.body;
    console.log(ctx.request.body);
    console.log(useId, title, note_type, note_content, c_time, m_time, head_img, nickname);
    // let c_time=new Date().toLocaleString();
    // let m_time=new Date().toLocaleString();
    await userService.insertNote([useId, title, note_type, note_content, c_time, m_time, head_img, nickname])
        .then(res => {
            console.log(res);
            if (res.affectedRows) {
                ctx.body = {
                    code: 200,
                    data: 'ok',
                    mess: '记录成功'
                }
            } else {
                ctx.body = {
                    code: '80001',
                    data: 'error',
                    mess: '记录失败'
                }
            }
        })
        .catch(err => {
            console.log(err);
            ctx.body = {
                code: '80001',
                data: err,
                mess: '服务器开小差啦'
            }
        })
})

module.exports = router